package controllers.manage.merchant;

import controllers.BaseController;
import controllers.auth.Secure;
import helper.GlobalConfig;
import jodd.util.StringUtil;
import me.chanjar.weixin.common.util.StringUtils;
import models.constants.DeletedStatus;
import models.merchant.Colocation;
import play.modules.paginate.JPAExtPaginator;
import play.mvc.Controller;
import play.mvc.With;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by youliangcheng on 17/7/11.
 */
@With(BaseController.class)
public class ColocationCtrl extends Controller {

    //列表页
    public static void loadList(Integer pageNumber,
                                String title){
        pageNumber = pageNumber == null ? 1 : pageNumber;

        Map<String , Object> searchMap = new HashMap<>();
        if(StringUtil.isNotBlank(title)) {
            searchMap.put("name", "%"+title+"%");
        }

        JPAExtPaginator<Colocation> resultPage = Colocation.findByCondition(searchMap, "id desc", pageNumber, GlobalConfig.PAGE_SIZE);
        render(resultPage, pageNumber, title);


    }

    //删除
    public static void deleteColocation(long id){
        Map<String , Object> resultMap = new HashMap<>();
        Colocation colocation = Colocation.findByColocationId(id);
        if(colocation == null){
            resultMap.put("success",false);
            resultMap.put("msg","数据不存在,可能已经被删除!");
            renderJSON(resultMap);
        }
        colocation.deleted = DeletedStatus.DELETED ;
        colocation.save();
        resultMap.put("success",true);
        flash.put("msg","删除成功!");
        renderJSON(resultMap);
    }

    //详情页
    public static void loadDetail(long id ,Integer pageNumber){
        Colocation colocation = new Colocation();
        if(id > 0 )
            colocation = Colocation.findById(id);
        render(colocation , pageNumber);
    }

    //保存
    public static void saveDetail( Colocation colocation , Integer pageNumber){
        Map<String ,Object> resultMap = new HashMap<>();
        if(StringUtils.isBlank(colocation.title)){

            flash.put("msg","标题不能为空!");
            redirect("/manage/merchant/ColocationCtrl/loadList/"+pageNumber);

        }
        Secure.setBaseInfo(colocation);
        if(colocation.id == null){
            colocation.loadKey();
            colocation.deleted = DeletedStatus.UN_DELETED;
            colocation.save();
        }else {
            colocation.update();
        }
        flash.put("msg","保存成功!");

        redirect("/manage/merchant/ColocationCtrl/loadList/"+pageNumber);

    }

}
